package cn.kennylee.codehub.springmvc.exceptionhandler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.core.Ordered;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <p> 全局异常处理类 </p>
 * <p>Created on 2025/8/25.</p>
 *
 * @author kennylee
 * @since 0.0.1
 */
@RestControllerAdvice
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@Slf4j
public class GlobalExceptionHandler implements Ordered {

    private final ExceptionResultFactory exceptionResultFactory;

    public GlobalExceptionHandler(ExceptionResultFactory exceptionResultFactory) {
        this.exceptionResultFactory = exceptionResultFactory;
    }

    /**
     * 全局兜底异常
     *
     * @param ex 异常
     * @return 结果
     */
    @ExceptionHandler(Exception.class)
    public ResultModel<?> handleGlobalException(Exception ex) {
        log.error("系统未知异常", ex);
        return exceptionResultFactory.createFailedResult(ResultErrorCode.SYS_ERROR, ex.getMessage());
    }

    @Override
    public int getOrder() {
        // 确保这是最后一个被调用的异常处理器
        return Ordered.LOWEST_PRECEDENCE;
    }
}
